package protocol.data;

import protocol.Frame;

public class Packet implements Frame {
	
	private byte type;
	private Frame data;
	
	public byte getType() {
		return this.type;
	}

	public void setType(byte type) {
		this.type = type;
	}

	public Frame getData() {
		return this.data;
	}

	public void setData(Frame data) {
		this.data = data;
	}
	
	/**
	 * Constructor
	 */
	public Packet() {
	}
	
	/**
	 * Constructor 
	 * @param bytes Supplied for the method parse()
	 */
	public Packet(byte[] bytes) {
		this.parse(bytes);
	}

	public byte[] build() {
		int dataLength = 0;
		if (this.getType() == 1) dataLength = 1451; // data packet
		if (this.getType() == 2) dataLength = 5; // reply packet
		byte[] data = new byte[dataLength + 1];
		/**
		 * Set the packet type
		 */
		data[0] = this.getType();
		/**
		 * Set the data
		 */
		System.arraycopy(
			this.getData().build(), 0, // source
			data, 1,  // destination
			dataLength); // copy length
		return data;
	}

	public void parse(byte[] bytes) {
		this.setType(bytes[0]);
		/**
		 * Type 1 -> DataPacket
		 */
		if (this.getType() == 1) {
			byte[] data = new byte[1451];
			System.arraycopy(
				bytes, 1, // source
				data, 0,  // destination
				1451); // copy length
			this.setData(new DataPacket(data));
		} else if (this.getType() == 2) {
			/**
			 * Type 2 -> ReplyPacket
			 */
			byte[] data = new byte[5];
			System.arraycopy(
				bytes, 1, // source
				data, 0,  // destination
				5); // copy length
			this.setData(new ReplyPacket(data));			
		} else {
			/**
			 * Erroneous type
			 */
		}
	}

}